package org.nextive.android.weightapp;

import java.util.ArrayList;

import org.nextive.android.weightapp.entities.AccountData;
import org.nextive.android.weightapp.utils.AccountsHelper;

import android.content.ContentProviderOperation;
import android.content.Context;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddContact extends AccountsHelper
{
	private Spinner spinnerAccounts;
	private EditText editTextContactName;
	private EditText editTextContactPhone;
	private Spinner spinnerContactPhoneType;
	private EditText editTextContactEmail;
	private Spinner spinnerContactEmailType;
	
	private Button buttonSaveContact;
	
	private ArrayList<Integer> contactPhoneTypes;
	private ArrayList<Integer> contactEmailTypes;
	
	private AccountData accountSelected;
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_contact);
		
		spinnerAccounts = (Spinner) findViewById(R.id.spinnerAccounts);
		editTextContactName = (EditText) findViewById(R.id.editTextContactName);
		editTextContactPhone = (EditText) findViewById(R.id.editTextContactPhone);
		spinnerContactPhoneType = (Spinner) findViewById(R.id.spinnerContactPhoneType);
		editTextContactEmail = (EditText) findViewById(R.id.editTextContactEmail);
		spinnerContactEmailType = (Spinner) findViewById(R.id.spinnerContactEmailType);
		
		fillSpinners();
		
		spinnerAccounts.setOnItemSelectedListener(new OnItemSelectedListener() 
		{
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,int position, long id) 
			{
				updateAccountSelection();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) 
			{
			}
		});
							
		buttonSaveContact = (Button) findViewById(R.id.buttonSaveContact);
		buttonSaveContact.setOnClickListener(new OnClickListener() 
		{			
			@Override
			public void onClick(View v) 
			{
				saveContact();
			}
		});
    }
	
	private void fillSpinners()
	{
		spinnerAccounts.setAdapter(getAccountAdapter());
		
		contactPhoneTypes = new ArrayList<Integer>();
		contactPhoneTypes.add(CommonDataKinds.Phone.TYPE_HOME);
		contactPhoneTypes.add(CommonDataKinds.Phone.TYPE_MOBILE);
		contactPhoneTypes.add(CommonDataKinds.Phone.TYPE_WORK);
		
		ArrayAdapter<String> contactPhonesTypesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		contactPhonesTypesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		for (Integer contactPhoneType: contactPhoneTypes)
		{
			contactPhonesTypesAdapter.add(ContactsContract.CommonDataKinds.Phone.getTypeLabel(this.getResources(), 
					  contactPhoneType, null).toString());
		}
		spinnerContactPhoneType.setAdapter(contactPhonesTypesAdapter);
			
		contactEmailTypes = new ArrayList<Integer>();
		contactEmailTypes.add(CommonDataKinds.Email.TYPE_HOME);
		contactEmailTypes.add(CommonDataKinds.Email.TYPE_MOBILE);
		contactEmailTypes.add(CommonDataKinds.Email.TYPE_WORK);
		
		ArrayAdapter<String> contactEmailTypesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		contactEmailTypesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		for (Integer contactEmailType: contactEmailTypes)
		{
			contactEmailTypesAdapter.add(ContactsContract.CommonDataKinds.Email.getTypeLabel(this.getResources(), 
					  contactEmailType, null).toString());
		}
		spinnerContactEmailType.setAdapter(contactEmailTypesAdapter);
	}
	
	private void updateAccountSelection() 
	{
		accountSelected = (AccountData) spinnerAccounts.getSelectedItem();
    }
	
	private void saveContact()
	{
		if (validateFields())
		{
			String name = editTextContactName.getText().toString();
			String phone = editTextContactPhone.getText().toString();
			String email = editTextContactEmail.getText().toString();
			
			int phoneType = contactPhoneTypes.get(spinnerContactPhoneType.getSelectedItemPosition());
			int emailType = contactEmailTypes.get(spinnerContactEmailType.getSelectedItemPosition());
			
			ArrayList<ContentProviderOperation> saveContactOperation = new ArrayList<ContentProviderOperation>();
			saveContactOperation.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
					.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountSelected.getType())
					.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountSelected.getName())
					.build());
			
			saveContactOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
	                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
	                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
	                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
	                .build());
			
			saveContactOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
	                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
	                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
	                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
	                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType)
	                .build());
			
			if (!email.isEmpty())
			{
				saveContactOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
		                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
		                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
		                .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
		                .withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType)
		                .build());
			}
			
			try 
			{
	            getContentResolver().applyBatch(ContactsContract.AUTHORITY, saveContactOperation);
	            Toast.makeText(this, R.string.contact_saved, Toast.LENGTH_SHORT).show();
	            finish();
	        }
			catch (Exception e) 
			{
	            Context context = getApplicationContext();
	            CharSequence error_creating_contact = getString(R.string.error_creating_contact);
	            Toast.makeText(context, error_creating_contact, Toast.LENGTH_LONG).show();
	        }
		}
	}
	
	private boolean validateFields()
	{
		if (getAccounts().isEmpty())
		{
			Toast.makeText(this, R.string.must_set_account, Toast.LENGTH_SHORT).show();
    		return false;
		}
		if (editTextContactName.getText().toString().isEmpty())
    	{
    		Toast.makeText(this, R.string.name_empty, Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	if (editTextContactEmail.getText().toString().isEmpty())
    	{
    		Toast.makeText(this, R.string.email_empty, Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	return true;
	}
}
